const url = require("url");
const querystring = require("querystring");
const fs = require("fs");
const path = require("path");
const router = require("koa-router")();
router.prefix("/profile");
const {
  ROLE_UPDATE_PHONE_SQL,
  ROLE_UPDATE_USER_INfO_SQL,
  ROLE_UPDATE_USER_AVATAR_SQL,
  ROLE_QUERY_AVATARPATH_SQL,
  ADDRESS_QUERY_USER_INFO_SQL,
  ADDRESS_UPDATE_ADDRESS_SQL,
  ADDRESS_INSERT_SQL,
  ADDRESS_DELETE_SQL,
  AGREEMENT_QUERY_AGREEMENT_SQL,
  STAGE_QUERY_STAGE_SQL,
  STAGE_UPDATE_STAGE_SQL,
  STAGE_INSERT_SQL,
  STAGE_DELETE_SQL,
  CRASHFEEDBACK_INSERT_NOT_WITH_IMGURLS_SQL,
  CRASHFEEDBACK_UPDATE_IMGURLS_SQL,
  COMPLAINTFEEDBACK_INSERT_NOT_WITH_IMGURLS_SQL,
  COMPLAINTFEEDBACK_UPDATE_IMGURLS_SQL,
  ORDER_QUERY_SQL,
  ORDER_QUERY_GOODSIMGURL_SQL,
  ORDER_UPDATE_SIGNFORSTATUS_AND_SIGNFORTIME_SQL,
} = require("../utils/sql");
const { query, update, insert, deleteFn } = require("../utils/db");
const { formatDate } = require("../utils/formatDate");
router.post("/updatePhoneNumber", async (ctx, next) => {
  const res = ctx.request.body;
  const { userPhone, userName } = res;
  if (userName && userPhone) {
    const queryParams = [userPhone, userName];
    const data = await update(ROLE_UPDATE_PHONE_SQL, queryParams);
    console.log(data);
    if (data) {
      ctx.body = {
        status: 200,
        msg: "更新成功!",
        data,
      };
    } else {
      ctx.body = {
        status: 500,
        msg: "更新失败!",
      };
    }
  }
});
router.get("/getUserInfo", async (ctx, next) => {
  const requestUrl = ctx.request.url;
  const arg = url.parse(requestUrl).query;
  const params = querystring.parse(arg);
  const name = params.userName;
  const queryParams = [name];
  if (name) {
    const data = await query(ADDRESS_QUERY_USER_INFO_SQL, queryParams);
    if (data) {
      ctx.body = {
        status: 200,
        msg: "获取数据成功!",
        data,
      };
    } else {
      ctx.body = {
        status: 500,
        msg: "获取数据失败!",
      };
    }
  }
});
router.post("/updateAddress", async (ctx, next) => {
  const res = ctx.request.body;
  const {
    newUserName,
    newUserPhone,
    newUserAddress,
    mode,
    oldUserName,
    oldUserPhone,
    userName,
  } = res;
  if (oldUserName && oldUserPhone && userName) {
    const queryParams = [
      newUserName,
      newUserPhone,
      newUserAddress,
      mode,
      oldUserName,
      oldUserPhone,
      userName,
    ];
    const data = await update(ADDRESS_UPDATE_ADDRESS_SQL, queryParams);
    if (data) {
      ctx.body = {
        status: 200,
        msg: "更新成功!",
        data,
      };
    } else {
      ctx.body = {
        status: 500,
        msg: "更新失败!",
      };
    }
  }
});
router.post("/insertAddress", async (ctx, next) => {
  const { userName, subUserName, subUserPhone, subUserAddress, mode } =
    ctx.request.body;
  if (userName && subUserName && subUserPhone && subUserAddress) {
    const queryParams = [
      userName,
      subUserName,
      subUserPhone,
      subUserAddress,
      mode,
    ];
    const data = await insert(ADDRESS_INSERT_SQL, queryParams);
    if (data) {
      ctx.body = {
        status: 200,
        msg: "插入数据成功",
        data,
      };
    } else {
      ctx.body = {
        status: 500,
        msg: "插入数据失败",
      };
    }
  }
});
router.post("/deleteAddress", async (ctx, next) => {
  const { userName, subUserName, subUserPhone, subUserAddress } =
    ctx.request.body;
  if (userName && subUserName && subUserPhone && subUserAddress) {
    const queryParams = [userName, subUserName, subUserPhone, subUserAddress];
    const data = await deleteFn(ADDRESS_DELETE_SQL, queryParams);
    if (data) {
      ctx.body = {
        status: 200,
        msg: "删除address表记录成功",
        data,
      };
    } else {
      ctx.body = {
        status: 500,
        msg: "删除address表记录失败",
      };
    }
  }
});
router.post("/uploadAvatar", async (ctx, next) => {
  const { userName, userPhone, content } = ctx.request.body;
  const imageExtension = content.match(/^data:image\/\w+;/)[0].slice(11, -1);
  const base64Data = content.replace(/^data:image\/\w+;base64,/, "");
  const dataBuffer = new Buffer.from(base64Data, "base64");
  const saveUrl = `${path.join(
    path.resolve(__dirname, "../"),
    "/public/image/profile/avatar/"
  )}${userName}_${userPhone}_${formatDate(
    new Date(),
    "yyyy年MM月dd日 hh点mm分"
  )}_${Math.floor(Math.random() * 1000)}.${imageExtension}`;
  let data = null;
  fs.writeFile(saveUrl, dataBuffer, async (err) => {
    if (err) {
      console.log(err);
    } else {
      const queryParams = [saveUrl, userName, userPhone];
      data = await update(ROLE_UPDATE_USER_AVATAR_SQL, queryParams);
    }
  });
  ctx.body = {
    msg: "咱也不知道成没成功,一般存储成功了,后续再看",
    data: "木鸡啊",
    saveUrl,
  };
});
router.post("/getAvatar", async (ctx, next) => {
  const { userName, userPhone } = ctx.request.body;
  console.log(userName, userPhone);
  if (userName && userPhone) {
    const queryParams = [userName, userPhone];
    const data = await query(ROLE_QUERY_AVATARPATH_SQL, queryParams);
    if (data) {
      const avatarPath = data[0].avatarPath;
      const base64Data = fs.readFileSync(avatarPath, "base64");
      if (base64Data) {
        ctx.body = {
          status: 200,
          msg: "获取图片成功",
          data: base64Data,
        };
      } else {
        ctx.compress = true;
        ctx.body = {
          status: 500,
          msg: "获取图片失败",
        };
      }
    }
  }
});
router.post("/updateUserInfo", async (ctx, next) => {
  const res = ctx.request.body;
  const {
    newUserName,
    newUserPhone,
    newUserPwd,
    oldUserName,
    oldUserPhone,
    oldUserPwd,
  } = res;
  if (oldUserName && oldUserPhone && oldUserPwd) {
    const queryParams = [
      newUserName,
      newUserPhone,
      newUserPwd,
      oldUserName,
      oldUserPhone,
      oldUserPwd,
    ];
    const data = await update(ROLE_UPDATE_USER_INfO_SQL, queryParams);
    if (data) {
      ctx.body = {
        status: 200,
        msg: "更新成功!",
        data,
      };
    } else {
      ctx.body = {
        status: 500,
        msg: "更新失败!",
      };
    }
  }
});
router.get("/getAgreement", async (ctx, next) => {
  const requestUrl = ctx.request.url;
  const arg = url.parse(requestUrl).query;
  const params = querystring.parse(arg);
  const agreement = params.agreement;
  const queryParams = [agreement];
  if (agreement) {
    const data = await query(AGREEMENT_QUERY_AGREEMENT_SQL, queryParams);
    data[0].content = JSON.parse(data[0].content);
    if (data) {
      ctx.body = {
        status: 200,
        msg: "获取数据成功!",
        data,
      };
    } else {
      ctx.body = {
        status: 500,
        msg: "获取数据失败!",
      };
    }
  }
});
router.get("/getStage", async (ctx, next) => {
  const requestUrl = ctx.request.url;
  const arg = url.parse(requestUrl).query;
  const params = querystring.parse(arg);
  const userName = params.userName;
  const queryParams = [userName];
  if (userName) {
    const data = await query(STAGE_QUERY_STAGE_SQL, queryParams);
    if (data) {
      ctx.body = {
        status: 200,
        msg: "获取数据成功!",
        data,
      };
    } else {
      ctx.body = {
        status: 500,
        msg: "获取数据失败!",
      };
    }
  }
});
router.post("/updateStage", async (ctx, next) => {
  const res = ctx.request.body;
  const { isTakeFromOneself, timeChoose, userName, address } = res;
  if (
    isTakeFromOneself &&
    (timeChoose || timeChoose === 0) &&
    userName &&
    address
  ) {
    const queryParams = [isTakeFromOneself, timeChoose, userName, address];
    const data = await update(STAGE_UPDATE_STAGE_SQL, queryParams);
    if (data) {
      ctx.body = {
        status: 200,
        msg: "更新成功!",
        data,
      };
    } else {
      ctx.body = {
        status: 500,
        msg: "更新失败!",
      };
    }
  }
});
router.post("/insertStage", async (ctx, next) => {
  const { userName, stageName, address } = ctx.request.body;
  if (userName && stageName && address) {
    const queryParams = [userName, stageName, address];
    const data = await insert(STAGE_INSERT_SQL, queryParams);
    if (data) {
      ctx.body = {
        status: 200,
        msg: "插入stage表成功",
        data,
      };
    } else {
      ctx.body = {
        status: 500,
        msg: "插入stage表失败",
      };
    }
  }
});
router.post("/deleteStage", async (ctx, next) => {
  const { userName, stageName, address } = ctx.request.body;
  if (userName && stageName && address) {
    const queryParams = [userName, stageName, address];
    const data = await deleteFn(STAGE_DELETE_SQL, queryParams);
    if (data) {
      ctx.body = {
        status: 200,
        msg: "删除stage表记录成功",
        data,
      };
    } else {
      ctx.body = {
        status: 500,
        msg: "删除stage表记录失败",
      };
    }
  }
});
router.post("/insertCrashFeedback", async (ctx, next) => {
  let {
    userPhone,
    crashType,
    desc,
    crashTime,
    contents = "[]",
  } = ctx.request.body;
  //1.存储图片
  const imgUrls = [];
  JSON.parse(contents).forEach((item, index) => {
    const imageExtension = item.match(/^data:image\/\w+;/)[0].slice(11, -1);
    const base64Data = item.replace(/^data:image\/\w+;base64,/, "");
    const dataBuffer = new Buffer.from(base64Data, "base64");
    const year = crashTime.split(" ")[0].split("-")[0];
    const month = crashTime.split(" ")[0].split("-")[1];
    const day = crashTime.split(" ")[0].split("-")[2];
    const hour = crashTime.split(" ")[1].split(":")[0];
    const minute = crashTime.split(" ")[1].split(":")[1];
    const crashTime2timeStamp = new Date(
      year,
      month,
      day,
      hour,
      minute
    ).getTime();
    const saveUrl = `${path.join(
      path.resolve(__dirname, "../"),
      "/public/image/profile/crashFeedback/"
    )}${userPhone}_${crashType}_${crashTime2timeStamp}_${index}.${imageExtension}`;
    imgUrls.push(saveUrl);
    fs.writeFile(saveUrl, dataBuffer, async (err) => {
      if (err) {
        console.log(err);
      }
    });
  });
  const queryParams1 = [userPhone, crashType, desc, crashTime];
  //2.插入数据前三项包括userPhone,crashType,desc
  const data1 = await insert(
    CRASHFEEDBACK_INSERT_NOT_WITH_IMGURLS_SQL,
    queryParams1
  );
  //3.更新imgUrls
  const queryParams2 = [
    JSON.stringify(imgUrls),
    userPhone,
    crashType,
    crashTime,
  ];
  const data2 = await update(CRASHFEEDBACK_UPDATE_IMGURLS_SQL, queryParams2);
  if (data1 && data2) {
    ctx.body = {
      status: 200,
      msg: "存储crashFeedback成功",
      data: JSON.stringify(imgUrls),
    };
  } else {
    ctx.body = {
      status: 500,
      msg: "存储crashFeedback失败",
    };
  }
});
router.post("/insertComplaintFeedback", async (ctx, next) => {
  let { complaintType, desc, contents = "[]" } = ctx.request.body;
  //1.存储图片
  const imgUrls = [];
  JSON.parse(contents).forEach((item, index) => {
    const imageExtension = item.match(/^data:image\/\w+;/)[0].slice(11, -1);
    const base64Data = item.replace(/^data:image\/\w+;base64,/, "");
    const dataBuffer = new Buffer.from(base64Data, "base64");
    const saveUrl = `${path.join(
      path.resolve(__dirname, "../"),
      "/public/image/profile/complaintFeedback/"
    )}${complaintType}_${index}.${imageExtension}`;
    imgUrls.push(saveUrl);
    fs.writeFile(saveUrl, dataBuffer, async (err) => {
      if (err) {
        console.log(err);
      }
    });
  });
  const timeStamp = new Date().getTime();
  const queryParams1 = [complaintType, desc, timeStamp];
  //2.插入数据前两项包括complaintType,desc
  const data1 = await insert(
    COMPLAINTFEEDBACK_INSERT_NOT_WITH_IMGURLS_SQL,
    queryParams1
  );
  //3.更新imgUrls
  const queryParams2 = [
    JSON.stringify(imgUrls),
    complaintType,
    desc,
    timeStamp,
  ];
  const data2 = await update(
    COMPLAINTFEEDBACK_UPDATE_IMGURLS_SQL,
    queryParams2
  );
  if (data1 && data2) {
    ctx.body = {
      status: 200,
      msg: "存储complaintFeedback成功",
      data: JSON.stringify(imgUrls),
    };
  } else {
    ctx.body = {
      status: 500,
      msg: "存储complaintFeedback失败",
    };
  }
});
router.post("/getUserOrder", async (ctx, next) => {
  const { userName, userPhone } = ctx.request.body;
  const queryParams = [userName, userPhone];
  if (userName && userPhone) {
    const data = await query(ORDER_QUERY_SQL, queryParams);
    if (data) {
      ctx.body = {
        status: 200,
        msg: "获取成功",
        data,
      };
    } else {
      ctx.body = {
        status: 500,
        msg: "获取失败",
      };
    }
  }
});
router.post("/getGoodsImage", async (ctx, next) => {
  const { userName, userPhone, goodsName } = ctx.request.body;
  const queryParams = [userName, userPhone, goodsName];
  if (userName && userPhone && goodsName) {
    const res = await query(ORDER_QUERY_GOODSIMGURL_SQL, queryParams);
    if (res) {
      const goodsImgURl = res[0].goodsImgURl;
      const data = fs.readFileSync(goodsImgURl, "base64");
      if (data) {
        ctx.body = {
          status: 200,
          msg: "获取商品图片成功",
          data,
        };
      } else {
        ctx.body = {
          status: 500,
          msg: "获取商品图片失败",
        };
      }
    }
  }
});
router.post("/updateSignForStatusAndSignForTime", async (ctx, next) => {
  const { signForStatus, userName, userPhone, goodsName } = ctx.request.body;
  if ((signForStatus, userName && userPhone && goodsName)) {
    const queryParams = [
      signForStatus,
      formatDate(new Date(), "yyyy年MM月dd日 hh点mm分"),
      userName,
      userPhone,
      goodsName,
    ];
    const data = await query(
      ORDER_UPDATE_SIGNFORSTATUS_AND_SIGNFORTIME_SQL,
      queryParams
    );
    if (data) {
      ctx.body = {
        status: 200,
        msg: "更新签收状态和签收时间成功",
        data,
      };
    } else {
      ctx.body = {
        status: 500,
        msg: "更新签收状态和签收时间失败",
      };
    }
  }
});

module.exports = router;
